package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.to.SkuHasStockVO;
import com.atguigu.common.tool.utils.Func;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 17495
 */
@Service("wareSkuService")
@AllArgsConstructor
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    private final ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String skuId = (String) params.get("skuId");
        String wareId = (String) params.get("wareId");
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                Wrappers.<WareSkuEntity>lambdaQuery()
                        .eq(Func.isNotEmpty(skuId), WareSkuEntity::getSkuId, skuId)
                        .eq(Func.isNotEmpty(wareId), WareSkuEntity::getWareId, wareId)
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        // 1. 判断 如果还没有这个库存记录新增
        List<WareSkuEntity> entities = list(Wrappers.<WareSkuEntity>lambdaQuery()
                .eq(WareSkuEntity::getSkuId, skuId)
                .eq(WareSkuEntity::getWareId, wareId)
        );

        if (Func.isEmpty(entities)) {
            WareSkuEntity skuEntity = WareSkuEntity.builder()
                    .skuId(skuId)
                    .stock(skuNum)
                    .wareId(wareId)
                    .stockLocked(0)
                    .build();
            //TODO 远程查询sku的名字，如果失败，整个事务无需回滚

            //TODO 还可以用什么办法让异常出现以后不回滚？高级
            try {
                R info = productFeignService.info(skuId);
                Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0) {
                    skuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception ignored) {

            }

            save(skuEntity);
        } else {
            update(Wrappers.<WareSkuEntity>lambdaUpdate()
                    .setSql("stock = stock + " + skuNum)
                    .eq(WareSkuEntity::getSkuId, skuId)
                    .eq(WareSkuEntity::getWareId, wareId)
            );
        }


    }

    @Override
    public List<SkuHasStockVO> getSkuHasStocks(List<Long> ids) {
        return ids.stream()
                .map(id -> {
                    SkuHasStockVO skuHasStockVO = new SkuHasStockVO();
                    skuHasStockVO.setSkuId(id);
                    Long sum = getObj(Wrappers.<WareSkuEntity>query().select("SUM(stock-stock_locked)")
                            .eq("sku_id", 1), o -> (Long) o);
                    skuHasStockVO.setHasStock(sum != null && sum > 0);
                    return skuHasStockVO;
                })
                .collect(Collectors.toList());
    }

}
